//
//  UtilClass.m
//  AsyncImages
//
//  Created by alex on 12-1-31.
//  Copyright (c) 2012年 develop4u.gr. All rights reserved.
//

#import "UtilClass.h"
#import "NSData+md5.h"
#include "Base64Transcoder.h"

@implementation UtilClass

+ (NSString *) md5FromData:(NSData*)data
{
    if (data) {
        return [data md5];
    }
    return nil;
}

+ (NSData*) Base64EncodeData:(NSData*)data
{
    if (nil == data || data.length == 0) {
        return nil;
    }
    
    size_t theResultLength = data.length*2;
    char * base64Result = malloc(theResultLength);

    Base64EncodeData(data.bytes, data.length, base64Result, &theResultLength);
    NSData *theData = [NSData dataWithBytes:base64Result length:theResultLength];
    
    free(base64Result);
    
    return theData;
}

+ (NSData*) Base64DecodeData:(NSData*)data
{
    if (nil == data || data.length == 0) {
        return nil;
    }
    
    size_t theResultLength = data.length;
    char * base64Result = malloc(theResultLength);
    
    Base64DecodeData(data.bytes, data.length, base64Result, &theResultLength);
    NSData *theData = [NSData dataWithBytes:base64Result length:theResultLength];
    
    free(base64Result);
    
    return theData;
}


+ (NSString *) md5FromString:(NSString*)data
{
    return [UtilClass md5FromData:[data dataUsingEncoding:NSUTF8StringEncoding]];
}

+ (NSString*) Base64EncodeString:(NSString*)data
{
    NSData * retData = [UtilClass Base64EncodeData:[data dataUsingEncoding:NSUTF8StringEncoding]];
    if (retData) {
        return [[[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding] autorelease]; 
    }
    
    return nil;
}

+ (NSString*) Base64DecodeString:(NSString*)data
{
    NSData * retData = [UtilClass Base64DecodeData:[data dataUsingEncoding:NSUTF8StringEncoding]];
    if (retData) {
        return [[[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding] autorelease]; 
    }
    
    return nil;
}

@end
